var http = require('http')
var textBody = require("body")
var jsonBody = require("body/json")
const { encode, decode } = require('url-encode-decode')
var url = require('url')
var low = require('lowdb')
var fs = require('fs')
const FileSync = require('lowdb/adapters/FileSync')
const Memory = require('lowdb/adapters/Memory')
var util = require('util')                                                       
var querystring = require('querystring')
const shortid = require('shortid')

var adapter = new FileSync('db.json')
//var adapter = new Memory()
const db = low(adapter);
db.defaults({ req: [] }).write();
var server = http.createServer(function (req, res) {
    var newurl = url.parse(req.url, true)
    if(newurl.pathname == "/favicon.ico"){ 
        return;
    }
    else if(newurl.pathname == "/"){
        fs.readFile('index.html',function(err,buffer){
            res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
            res.end(buffer);
        })
    }
    else if(newurl.pathname == "/newurl"){
        var data = {
            "id": shortid.generate(),
            "date": new Date().valueOf()
        };
        jsonBody(req, res,function(err,body){
            remove(body.path)
            data.path = body.path;
            data.value = body.value;
            data['content-type'] = body.contentType;
            insert(data);
            res.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' });
            res.end( JSON.stringify({status:1,msg:"success"}) );
        })
    }
    else if(newurl.pathname == "/data"){
        var arr = db.get('req').sortBy('date').value();
        arr = arr.reverse();
        res.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' });
        res.end( JSON.stringify(arr) );
        return ;
    }
    else if(newurl.pathname == "/delete"){
        var arr = db.get('req').remove({id: newurl.query.id }).write();
        res.writeHead(200,{'Content-Type':"text/plain"});
        res.end("1");
        return ;
    }
    else if( newurl.pathname == "/clear") {
        db.get('req').remove({}).write();
        var html = "remove completed";
        res.writeHead(200,{ 'Content-Type': 'text/html;charset=utf-8' })
        res.end(html)
    }
    else {
        var pathName = newurl.pathname;
        var decodePath = decode(pathName)
        var result = search(decodePath);
        console.log(result)
        if(result){
            result.lastAccess= new Date().valueOf();
            updateLastAccess(result.id);
            res.writeHead(200,{'Content-Type':result["content-type"]})
            res.end(result.value);
        }else{
            res.writeHead(404,{'Content-Type':"text/plain;charset=utf-8"})
            res.end();
        }
    }
});

function insert(data){
    db.get('req').push(
             data   
    ).write()
}
function remove(path){
    db.get('req').remove({path:path}).write();
}
function search(path){
    return db.get('req').find({path:path}).value();
}
function updateLastAccess(id){
    db.get('req')
  .find({ id: id })
  .assign({ lastAccess: new Date().valueOf()})
  .write()
}
server.listen(3003, function () {
    console.log('server start at 3003 port');
});